import VueRouter from 'vue-router'
import Vue from 'vue'
// 导入登陆页面
import auth from '@/utils/token'
import { Message } from 'element-ui'

// 直接加载，把所有文件打包到一个 js 中
// import Login from '@/views/login'
// import Layout from '@/views/Layout.vue'
// import Home from '@/views/home'
// import Article from '@/views/article'
// import Publish from '@/views/publish'

// 按需加载(懒加载)，把每个文件拆分成一个 js 文件
const Login = () => import('@/views/login')
const Layout = () => import('@/views/publish/Layout.vue')
const Home = () => import('@/views/home')
const Article = () => import('@/views/article')
const Publish = () => import('@/views/publish')

const Newhome = () => import('@/views/newhome')
// 注册全局路由组件
Vue.use(VueRouter)
// 创建路由实例
const router = new VueRouter({

  // 配置路由表
  routes: [
  // 路径path与组件component的映射关系
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      children: [
        { path: '', component: Home },
        { path: 'article', component: Article },
        { path: 'publish/:id?', component: Publish },
        { path: 'newhome', component: Newhome }
      ]
    }
  ]
})
// 导航守卫
// to 去哪里
// from 从哪里来
// next 放行函数
router.beforeEach((to, from, next) => {
  const token = auth.getToken()
  // 非登录页 同时无token，就跳转到登录页
  if (to.path !== '/login' && !token) {
    // 非vue组件 需要单独导入message
    Message.error('登陆信息失效，请重新登陆')
    return next('/login')
  }

  next()
})
// 导出路由实例
export default router
